package com.wr.controllers;

import com.wr.pojos.PermissionEntity;
import com.wr.pojos.UserEntity;
import com.wr.pojos.UserImageEntity;
import com.wr.services.UserImageService;
import com.wr.services.UserService;
import com.wr.utils.EhcacheUtils;
import com.wr.utils.UpLoadFileUtil;
import com.wr.utils.Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName:   IndexController
 * @Description: 首页controller
 * @author 吴睿
 * @date 2016-11-29
 */
@Controller
@RequestMapping("/")
public class IndexController {

    @Resource
    private UserService userService;

    @Resource
    private UserImageService userImageService;

    /**
     * 进入登录页
     * @return  返回值
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    /**
     * 登录
     * @param user      传入数据
     * @param result    验证
     * @param model     视图模型
     * @return          返回值
     */
    @RequestMapping("/login")
    public String login(UserEntity user, BindingResult result,Model model){
        try {
            Subject subject = SecurityUtils.getSubject();
            // 已登陆则 跳到首页
            if (subject.isAuthenticated()) {
                return "layui";
            }
            if (result.hasErrors()) {
                model.addAttribute("error", "参数错误！");
                return "redirect:toLogin";
            }
            // 身份验证
            subject.login(new UsernamePasswordToken(user.getMobile(), Utils.MD5(user.getPassword())));
            UserEntity userEntity = (UserEntity) subject.getPrincipal();
            EhcacheUtils.put("myCache","userEntity",userEntity);
        } catch (AuthenticationException e) {
            // 身份验证失败
            model.addAttribute("error", "用户名或密码错误 ！");
            return "redirect:toLogin";
        }
        return "redirect:layui.do";
    }

    /**
     * 进入layui首页
     * @param model 视图模型
     * @return  返回值
     */
    @RequestMapping("/layui")
    public String layui(Model model){
        UserEntity userEntity = (UserEntity) EhcacheUtils.get("myCache","userEntity");
        List<PermissionEntity> list = userEntity.getRootMenuList();
        model.addAttribute("list",list);
        model.addAttribute("userEntity",userEntity);
        return "layui/layui";
    }

    @RequestMapping("/unauthorized")
    public String unauthorized(){
        return "unauthorized";
    }

    /**
     * 注册
     * @param user  传入数据
     * @return  返回值
     */
    @RequestMapping("/register")
    @ResponseBody
    public Map<String,Object> register(UserEntity user){
        Map<String,Object> map = new HashMap<>();
        UserEntity userEntity = userService.selectUserByNameAndMobile(user.getUserName(),user.getMobile());
        if(userEntity==null){
            userService.addUser(user);
            map.put("msg","注册成功！");
        }else{
            map.put("msg","用户已存在");
        }
        return map;
    }

    /**
     * 退出
     * @return  返回值
     */
    @RequestMapping("/loginOut")
    public String loginOut(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        EhcacheUtils.remove("myCache","userEntity");
        return "redirect:toLogin.do";
    }

    /**
     * 下载文件
     * @param response  返回
     * @param fileName  文件名
     * @throws Exception    异常
     */
    @RequestMapping("/downloadFile")
    @ResponseBody
    public void downloadFile(HttpServletResponse response,String fileName) throws Exception{
        String path = "C:\\Users\\Administrator\\Desktop\\手机相册\\"+fileName;
        /*String path = "/data/image/"+fileName;*/
        File file = new File(path);// path是根据日志路径和文件名拼接出来的
        String filename = file.getName();// 获取日志文件名称
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        os.write(buffer);// 输出文件
        os.flush();
        os.close();
    }

    /**
     * 上传文件
     * @param request   请求
     * @throws IOException IO异常
     * @return 返回值
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
    public Map<String,Object> uploadFile(HttpServletRequest request) throws IOException{
        Map<String,Object> map = new HashMap<>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("myFile");
        byte[] buffer = multipartFile.getBytes();
        FileOutputStream fo;
        fo = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\手机相册"+File.separator+multipartFile.getOriginalFilename());
        fo.write(buffer);
        fo.flush();
        fo.close();

        //注释内容为ftp上传模式
        /*CommonsMultipartFile cf = (CommonsMultipartFile) multipartFile;
        InputStream inputStream = cf.getInputStream();
        UpLoadFileUtil.uploadFile("139.199.39.171",21,"ftpwurui",
                "123456","/data/image/headImg",multipartFile.getOriginalFilename(),inputStream);*/

        UserImageEntity imageEntity = new UserImageEntity();
        imageEntity.setImagePath("imgePath");
        imageEntity.setImageName(multipartFile.getOriginalFilename());
        userImageService.addImage(imageEntity);
        map.put("result","success");
        return map;
    }

    /**
     * 进入扫雷
     * @return  返回值
     */
    @RequestMapping("/playGame")
    public String playGame(){
        return "game";
    }

    /**
     * 进入首页
     * @return
     */
    @RequestMapping("/index")
    public String index(){
        return "layui/index";
    }
}
